<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>管理员信息</span>
      </div>
      <div>
        <el-form>
          <el-form-item label="管理员ID:">{{ userInfo.id }}</el-form-item>
          <el-form-item label="账号:">{{ userInfo.account }}</el-form-item>
          <el-form-item label="用户组:">{{ userInfo.userGroup }}</el-form-item>
          <el-form-item label="创建时间:">{{ userInfo.ctime | formatDatenyrsfm }}</el-form-item>
          <el-form-item label="用户头像:">
            <el-upload class="avatar-uploader" :action="API + '/users/avatar_upload'" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="userInfo.imgUrl" :src="userInfo.imgUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-button type="primary" @click="handleUpdateAvatar">修改头像</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { updateAvatar } from '@/api/user'
import { loacl } from '@/utils/local'
export default {
  data() {
    return {
      API: 'http://127.0.0.1:5000',
      userInfo: {},
      imageUrl: ''
    }
  },
  created() {
    this.userInfo = loacl.get('userInfo')
  },
  methods: {
    // 上传成功，后端响应函数
    handleAvatarSuccess(res) {
      let { code, imgUrl } = res
      if (code === 0) {
        this.userInfo.imgUrl = this.API + imgUrl
        this.newImgName = imgUrl
      }
    },
    // 上传之前触发,一般限制图片大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 修改头像
    async handleUpdateAvatar() {
      let res = await updateAvatar({ imgUrl: this.newImgName.substr(21) })
      let { code } = res.data
      if (code === 0) {
        this.$bus.$emit('upadteAvatar')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-form-item {
  // background-color: red;
  border-bottom: 1px solid #eee;
}
/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
